﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Dimok;

namespace Dimok.Web.UI {
	public class DataContextHolder : ContentControl {
		public string AncestorType { get; set; }



		public object Ancestor {
			get { return (object)GetValue(AncestorProperty); }
			set { SetValue(AncestorProperty, value); }
		}
		public static readonly DependencyProperty AncestorProperty =
				DependencyProperty.Register("Ancestor", typeof(object), typeof(DataContextHolder), new PropertyMetadata((d,e) => {
					((DataContextHolder)d).Ancestor = e.NewValue;
					((DataContextHolder)d).AncestorDataContext = (e.NewValue as FrameworkElement).DataContext;
				}));



		public object AncestorDataContext {
			get { return (object)GetValue(AncestorDataContextProperty); }
			set { SetValue(AncestorDataContextProperty, value); }
		}

		// Using a DependencyProperty as the backing store for AncestorDataContext.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty AncestorDataContextProperty =
				DependencyProperty.Register("AncestorDataContext", typeof(object), typeof(DataContextHolder), null);



		public object Data {
			get { return (object)GetValue(DataProperty); }
			set { SetValue(DataProperty, value); }
		}
		public static readonly DependencyProperty DataProperty =
				DependencyProperty.Register("Data", typeof(object), typeof(DataContextHolder),
					new PropertyMetadata(null));

		public DataContextHolder() {
			HorizontalContentAlignment = HorizontalAlignment.Stretch;
			VerticalContentAlignment = VerticalAlignment.Stretch;
			Loaded += new RoutedEventHandler(DataContextHolder_Loaded);
		}

		void DataContextHolder_Loaded(object sender, RoutedEventArgs e) {
			if (this.AncestorType + "" != "") {
				var fe = (sender as DependencyObject).GetParent(this.AncestorType);
				// TEST: This is for coulumn dragging in DateGrid
				if (fe == null) return;
				if (!(fe is FrameworkElement))
					throw new System.NotSupportedException("Ancestors other then derrived from " + typeof(FrameworkElement).Name + " are not supported,");
				this.Ancestor = fe as FrameworkElement;
			}
		}
	}
}
